package com.winning.sx.microframework.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
//import org.icepdf.core.pobjects.Stream;
//import org.jpedal.jbig2.io.StreamReader;

import net.sf.json.JSONObject;

public class HttpUtils
{
  private static Logger log = Logger.getLogger(HttpUtils.class);
  //	public static String postJson(String urlstr, String data) {
  public static String postJson(String urlstr, Map<String, Object> params) {
		try {
			org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
			HttpPost method = new HttpPost(urlstr);
			method.setHeader("Content-Type","application/json");
//          method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
			log.debug("发出去的json字符串是:"+JsonUtils.objectToJson(params));
			ByteArrayEntity reqEntity = new ByteArrayEntity(JsonUtils.objectToJson(params).getBytes("UTF-8"));
			reqEntity.setContentEncoding("UTF-8");
			method.setEntity(reqEntity);
			HttpResponse response = null;
			long requestBeginTime = System.currentTimeMillis();
			log.debug("request postJson 开始时间:"+requestBeginTime);
			response = httpclient.execute(method);//还是将近4秒
			log.debug("requst postJson 花费的时间是:"+(System.currentTimeMillis()-requestBeginTime));
			if (response != null) {
				// HttpEntity resEntity = response.getEntity();
				String returnStr = EntityUtils.toString(response.getEntity());
				log.info("返回的字符串是:"+returnStr);
				return returnStr;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
  
  /**
   * 
   * 
   * 
   *    public static string HttpPost(string posturl, string postData)
        {

            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            //Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
            Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                //instream = request.GetResponse().GetResponseStream();
                Encoding encoding_res = System.Text.Encoding.GetEncoding("utf-8");
                sr = new StreamReader(instream, encoding_res);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
   * @param urls
   * @param data
   * @return
   */
  public static String postByByte(String urls, String dataStr){
	  log.debug("发送前的字符串是:"+dataStr);
	  try {
          byte[] data = dataStr.getBytes("gb2312");
          URL url = new URL(urls);
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setRequestMethod("POST");
          connection.setUseCaches(false);
          connection.setInstanceFollowRedirects(true);
          connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          connection.setRequestProperty("content-length", data.length+"");
          connection.connect();
          DataOutputStream out = new DataOutputStream(connection.getOutputStream());
          out.write(data, 0, data.length);
          out.flush(); 
          out.close();

          BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		  String lines;
          StringBuffer sb = new StringBuffer("");
          while ((lines = in.readLine()) != null) {
             // lines = URLDecoder.decode(lines, "utf-8");
              lines = new String(lines.getBytes("utf-8"));
        	  sb.append(lines);
          }
		  in.close();
		 // log.info("postUrl-------sb.toString()--"+sb.toString());
		  return sb.toString();
	} catch (Exception e) {
		e.printStackTrace();
		// TODO: handle exception
	}
	return "";
  }
  
  
  
  public static String postUrl(String urls, String data){
	  try {
		  URL urlstr = new URL(urls);
		  URLConnection urlConnection = urlstr.openConnection();
		  urlConnection.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=utf-8");//设置http的mime
		  urlConnection.setDoOutput(true);
		  PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
		  String postContent = new String(data);
		  out.println(postContent);//写出http协议的数据，和网页上的click后做的事一样的
		  out.close();
		  urlConnection.connect();
		  BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
		  String lines;
          StringBuffer sb = new StringBuffer("");
          while ((lines = in.readLine()) != null) {
              lines = URLDecoder.decode(lines, "utf-8");
              sb.append(lines);
          }
		  in.close();
		  return sb.toString();
	} catch (Exception e) {
		e.printStackTrace();
		// TODO: handle exception
	}
	return "";
  }
  
  public static String postTextJson(String urls, String data){
	  long startTime = System.currentTimeMillis();
	  log.debug("发送json数据开始,data-->"+data);
	  try {
          //创建连接 
          URL url = new URL(urls);
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setRequestMethod("POST");
          connection.setUseCaches(false);
          connection.setInstanceFollowRedirects(true);
          connection.setRequestProperty("Content-Type", "application/json");
          connection.connect();
          // POST请求 
          DataOutputStream out = new DataOutputStream(connection.getOutputStream());
          JSONObject obj = new JSONObject();
          String json = java.net.URLEncoder.encode(obj.toString(), "utf-8");
          out.writeBytes(json);
          out.flush();
          out.close();
          // 读取响应 
          BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          String lines;
          StringBuffer sb = new StringBuffer("");
          while ((lines = reader.readLine()) != null) {
              lines = URLDecoder.decode(lines, "utf-8");
              sb.append(lines);
          }
          log.debug("返回的数据格式是:"+sb.toString());
          reader.close();
          // 断开连接 
          connection.disconnect(); 
          log.debug("执行方法时间为:"+(System.currentTimeMillis()-startTime));
          return sb.toString();
      } catch (MalformedURLException e) { 
    	  log.debug(e.getMessage());
    	  log.debug(e.getMessage());
          e.printStackTrace(); 
      } catch (UnsupportedEncodingException e) { 
    	  log.debug(e.getMessage());
    	  log.error(e.getMessage());
          e.printStackTrace(); 
      } catch (Exception e) { 
    	  log.debug(e.getMessage());
    	  log.error(e.getMessage());
          e.printStackTrace(); 
      }
	  
	  return "";
  }
  	
  
  public static String postText(String urls, String data) {
	log.debug("发送的数据是:"+data);
    try {
      StringBuffer sb = new StringBuffer();
      URL url = new URL(urls);
      HttpURLConnection httpsConn =(HttpURLConnection) url.openConnection();
      httpsConn.setUseCaches(false);
      httpsConn.setDoOutput(true);
      httpsConn.setDoInput(true);
      httpsConn.setInstanceFollowRedirects(true);
      httpsConn.setRequestMethod("POST");
      OutputStreamWriter post = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8");
      post.write(data);
      post.flush();
      BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8"));
      String inputLine;
      while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
      }
      post.close();
      in.close();
      log.debug("返回的数据是:"+sb.toString());
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }

  public static String post(String urlStr, String xmlStr)
  {
    try
    {
      URL url = new URL(urlStr);
      URLConnection con = url.openConnection();
      con.setDoOutput(true);
      con.setRequestProperty("Pragma:", "no-cache");
      con.setRequestProperty("Cache-Control", "no-cache");
      con.setRequestProperty("Content-Type", "text/xml");
      OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
      out.write(new String(xmlStr.getBytes("UTF-8")));
      out.flush();
      out.close();
      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
      StringBuffer sb = new StringBuffer();
      String line = "";
      for (line = br.readLine(); line != null; line = br.readLine()) {
        sb.append(line);
      }
      return sb.toString();
    } catch (MalformedURLException e) {
      e.printStackTrace();
      return "";
    } catch (IOException e) {
      e.printStackTrace(); }
    return "";
  }

  public static List<String> postBackList(String urlStr, String xmlStr)
  {
    try
    {
      List strList = new ArrayList();
      URL url = new URL(urlStr);
      URLConnection con = url.openConnection();
      con.setDoOutput(true);
      con.setRequestProperty("Pragma:", "no-cache");
      con.setRequestProperty("Cache-Control", "no-cache");
      con.setRequestProperty("Content-Type", "text/xml");
      OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
      out.write(new String(xmlStr.getBytes("UTF-8")));
      out.flush();
      out.close();
      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

      String line = "";
      for (line = br.readLine(); line != null; line = br.readLine()) {
        strList.add(line);
      }
      return strList;
    } catch (MalformedURLException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace(); }
    return null;
  }

  
  
  public static String post(String url, Map<String, Object> params)
  {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String body = null;

    log.info("create httppost:" + url);
    HttpPost post = postForm(url, params);

    body = invoke(httpclient, post);

    httpclient.getConnectionManager().shutdown();

    return body;
  }
  
  private static HttpPost postForm(String url, Map<String, Object> params)
  {
    HttpPost httpost = new HttpPost(url);
    List nvps = new ArrayList();

    Set<String>  keySet = params.keySet();
    for (String key : keySet)
      nvps.add(new BasicNameValuePair(key, String.valueOf(params.get(key).toString())));
    try
    {
      log.debug("set utf-8 form entity to httppost");
      httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    return httpost;
  }

  private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost)
  {
	long requestBeginTime = System.currentTimeMillis();
	log.debug("request开始时间:"+requestBeginTime);
    HttpResponse response = sendRequest(httpclient, httpost);
    log.debug("requst花费的时间是:"+(System.currentTimeMillis()-requestBeginTime));
    long responseBeginTime = System.currentTimeMillis();
    log.debug("response开始时间:"+responseBeginTime);
    String body = paseResponse(response);
    log.debug("response响应花费的时间是:"+(System.currentTimeMillis()-responseBeginTime));
    return body;
  }
  
  private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) {
	    log.debug("execute post...");
	    HttpResponse response = null;
	    try
	    {
	     long httpPostStartTime = System.currentTimeMillis();
	     log.debug("execute post  httpPostStartTime:"+httpPostStartTime);
	     httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
	     RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
	     response = httpclient.execute(httpost);//这里花费了4秒钟
	    // http://10.10.10.20:10000/api/identity/get
	     log.debug("execute post  httpPost time is :"+(System.currentTimeMillis()-httpPostStartTime));
	    }
	    catch (ClientProtocolException e) {
	      e.printStackTrace();
	    }
	    catch (IOException e) {
	      e.printStackTrace();
	    }
	    return response;
	  }
  
  
  
  
  
  public static String posts(String url, Map<String, Object> params) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String body = null;

    log.debug("create httppost:" + url);
    HttpPost post = postForms(url, params);
    log.debug(":");
    body = invoke(httpclient, post);

    httpclient.getConnectionManager().shutdown();

    return body;
  }

  public static String get(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String body = null;

    log.debug("create httppost:" + url);
    HttpGet get = new HttpGet(url);
    body = invoke(httpclient, get);

    httpclient.getConnectionManager().shutdown();

    return body;
  }


  private static String paseResponse(HttpResponse response) {
    log.debug("get response from http server..");
    HttpEntity entity = response.getEntity();

    log.debug("response status: " + response.getStatusLine());
    String charset = EntityUtils.getContentCharSet(entity);

    String body = null;
    try {
      body = EntityUtils.toString(entity);
    }
    catch (ParseException e)
    {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }

    return body;
  }

 

  
  private static HttpPost postForms(String url, Map<String, Object> params)
  {
    HttpPost httpost = new HttpPost(url);
    JSONObject obj = JSONObject.fromObject(params);
    List nvps = new ArrayList();
    nvps.add(new BasicNameValuePair("params", obj.toString()));
    try {
      log.debug("set utf-8 form entity to httppost");
      httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    return httpost;
  }

  public static int sendMsg(String url, Map<String, String> params)
  {
    int statuscode = 0;
    try {
      HttpClient httpclient = new HttpClient();
      PostMethod post = new PostMethod(url);

      post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      post.getParams().setParameter("http.protocol.content-charset", "utf-8");
      if ((params != null) && (!(params.isEmpty()))) {
        for (String key : params.keySet()) {
        	if(params.get(key)!=null)
        		post.addParameter(key, params.get(key).toString());
        }
      }

      httpclient.executeMethod(post);
      statuscode = post.getStatusCode();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    return statuscode;
  }

  public static void main(String[] args) {
  /*  Map params = new HashMap();

    params.put("cSystemId", "分级诊疗系统");
    params.put("cSourceAddress", "127.0.0.1");
    params.put("cContent", "患者张三的验证码是043032。");
    params.put("cMobile", "15934044884");
    params.put("iMsgType", "100244");

    int statuscode = sendMsg("http://localhost:8081/sms/message", params);
    if (201 == statuscode)
      System.out.println("消息写入成功");*/
	//  String url="http://web.mathbeauty.cn";
	//  byte[] dataStr = "billStartDate=&billEndDate=&paytype=5".getBytes();
	//  HttpUtils.postByByte("http://localhost:8080/WebChat/wnQuery.action", "billStartDate=&billEndDate=&paytype=5");
	 // String url="http://a.sxsrmyy.com:6019/WebChat/department";
	 // HttpUtils.post(url, new HashMap<String,Object>());
	  Map<String,Object> maps = new HashMap<>();
	  maps.put("u_loginname", "zhangjh");
	  maps.put("u_password", "123456");
	  maps.put("u_cellphone", "13456789898");
	  postTextJson("http://192.168.1.138:8080/rbacMgr/registUser.action", JsonUtils.objectToJson(maps));
  }

  public static String postgb2312(String url, Map<String, Object> params)
  {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String body = null;

    log.debug("create httppost:" + url);
    HttpPost post = postFormgb2312(url, params);

    body = invoke(httpclient, post);

    httpclient.getConnectionManager().shutdown();

    return body;
  }

  private static HttpPost postFormgb2312(String url, Map<String, Object> params)
  {
    HttpPost httpost = new HttpPost(url);
    List nvps = new ArrayList();

    Set<String> keySet = params.keySet();
    for (String key : keySet) {
      nvps.add(new BasicNameValuePair(key, String.valueOf(params.get(key).toString())));
    }
    try
    {
      httpost.setEntity(new UrlEncodedFormEntity(nvps, "gb2312"));
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    return httpost;
  }

}